package com.mall.order.mq.order;

import com.mall.order.dal.entitys.Member;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.MemberMapper;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.List;
@Slf4j
@Component
public class DelayOrderConsumerReminder {

    private DefaultMQPushConsumer consumer;

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    OrderItemMapper orderItemMapper;


    @PostConstruct
    public void init (){

        consumer = new DefaultMQPushConsumer("delay_message_reminder");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        try {
            consumer.subscribe("orderReminder","*");

            consumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    for (MessageExt messageExt : list) {

                        String orderIdStr = new String(messageExt.getBody());

                        //判断订单是否支付
                        Order order = orderMapper.selectByPrimaryKey(orderIdStr);
                        //已支付直接跳出循环
                        if (order.getStatus() > 1) {
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }

                        if ("orderReminder".equals(messageExt.getTopic())) {
                            //发送提示邮件
                            sendEmail(orderIdStr);
                            log.info("邮件发送成功");
                        }
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            consumer.start();

        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void sendEmail(String orderIdStr) {

        //根据orderId获取订单信息中userId
        Order order = orderMapper.selectByPrimaryKey(orderIdStr);
        //根据userId回去注册邮箱
        Member member = memberMapper.selectByPrimaryKey(order.getUserId());
        //根据 orderId获取订单详情
        Example orderItemExample = new Example(OrderItem.class);
        orderItemExample.createCriteria().andEqualTo("orderId",orderIdStr);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject("[多来买商城] 订单未支付提醒");
        message.setFrom("995872646@qq.com");
        message.setTo(member.getEmail());
        StringBuilder text = new StringBuilder();
        text.append(member.getUsername()+" 亲！您于")
                .append(format.format(order.getCreateTime()))
                .append("购买了："+"\r\n");
        for (OrderItem orderItem : orderItems) {
            text.append(orderItem.getTitle())
                    .append("*"+orderItem.getNum()+"件"+"\r\n");
        }
        text.append("由于亲长时间未付款，五分钟后该订单会被系统取消，请点击下方链接快速登录并支付")
                .append("\r\n"+"http://localhost:9999/#/user/orderList");

        message.setText(text.toString());

        javaMailSender.send(message);
    }
}
